package com.icloud.admin.domain;

import com.icloud.framework.domain.model.AuditingEntity;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity(name = "sys_users")
@EntityListeners(AuditingEntityListener.class)
public class User extends AuditingEntity {
    private String username;
    private String password;
    private boolean enabled;
    private String description;

    @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    @JoinTable(name = "sys_user_role_relation",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")})
    private Set<Role> roles = new HashSet<Role>();

    public User() {
    }

    /**
     * 构造方法
     *
     * @param username    用户名
     * @param description 描述
     */
    public User( String username, String description) {

        setUsername(username);
        this.enabled = true;
        this.password = "123456";
        this.description = description;

    }

    /**
     * 禁用用户
     */
    public void disable() {
        this.enabled = false;
    }

    /**
     * 启用用户
     */
    public void enable() {
        this.enabled = true;
    }



    /**
     * 更新用户属性
     *
     * @param description 描述
     */
    public void changeProps(String description) {

        this.description = description;

    }

    /**
     * 为用户分配角色
     *
     * @param role 角色
     */
    public void assignRole(Role role) {
        this.assertArgumentNotNull(role, "选择的角色不存在");
        this.roles.add(role);
    }

    /**
     * 撤销用户分配的角色
     *
     * @param role
     */
    public void undoAssignedRole(Role role) {
        this.roles.remove(role);

    }

    protected void setUsername(String username) {
        this.username = username;
    }

}
